<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success lightgreen" v-if="!scope.row.cat_deleted"></i>
          <i class="el-icon-error red" v-else></i>
        </template>
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <template slot="operate" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditCateDialog(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <!-- <el-table :data="cateList" border>
      <el-table-column label="#" type="index"></el-table-column>
      <el-table-column label="分类名称" prop="cat_name"></el-table-column>
      <el-table-column label="是否有效" prop="index"></el-table-column>
      <el-table-column label="排序">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="index" width="200px">
        <template>
          <el-button type="primary" icon="el-icon-eidt" size="mini">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini">编辑</el-button>
        </template>
      </el-table-column>
      </el-table>-->

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 30]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog title="添加分类" :visible.sync="addCateDialogVisible" width="40%" @close="clearCateForm">
      <el-form :model="addCateForm" :rules="addCateRules" ref="addCateFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selecedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChange"
            expand-trigger="hover"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类的对话框 -->
    <el-dialog title="编辑分类" :visible.sync="editCateDialogVisible" width="40%" @close="clearEditForm">
      <el-form :model="editCateForm" :rules="addCateRules" ref="editCateFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selecedKeys2"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChange"
            disabled
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [],
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'level'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operate',
          minWidth: '200px'
        }
      ],
      // 添加分类对话框的可见性
      addCateDialogVisible: false,
      // 添加分类表单对应的对象
      addCateForm: {
        cat_pid: 0,
        cat_name: '',
        // 默认添加的是一级分类
        cat_level: 0
      },
      // 添加分类表单对应的验证规则
      addCateRules: {
        cat_name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' }
        ]
      },
      // 父级分类的列表
      parentCateList: [],
      // 被选中的父级分类对应的数组
      selecedKeys: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 当前编辑分类的id
      curEditId: 0,
      // 编辑分类对话框可见性
      editCateDialogVisible: false,
      // 编辑分类对话框对应的对象
      editCateForm: {},
      // 编辑分类时选中的对应分类
      selecedKeys2: []
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.cateList = res.data.result
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange(page) {
      this.queryInfo.pagenum = page
      this.getCateList()
    },
    // 显示添加分类对话框
    showAddCateDialog() {
      this.addCateDialogVisible = true
      this.getParentCateList()
    },
    // 获取父级分类列表
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) return this.$message.error('获取父级分类失败！')
      this.parentCateList = res.data
    },
    // 关闭添加分类按钮时
    clearCateForm() {
      this.$refs.addCateFormRef.resetFields()
      this.selecedKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    // 父级分类联动改变
    parentCateChange() {
      if (this.selecedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selecedKeys[this.selecedKeys.length - 1]
        this.addCateForm.cat_level = this.selecedKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 添加分类
    addCate() {
      this.$refs.addCateFormRef.validate(validate => {
        if (!validate) return this.$message('您输入的格式有误')
        this.$http.post('categories', this.addCateForm)
          .then(res => {
            res = res.data
            if (res.meta.status !== 201) return this.$message.error('添加分类失败！')
            this.$message.success('添加分类成功！')
            this.getCateList()
            this.addCateDialogVisible = false
          })
          .catch(() => {
            this.$message.error('serve error!')
          })
      })
    },
    // 显示编辑分类对话框
    async showEditCateDialog(id) {
      this.curEditId = id
      this.editCateDialogVisible = true
      this.getParentCateList()
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取分类信息失败！')
      this.editCateForm = res.data
      // 显示当前分类的父级分类
      this.showCurCatePid(this.editCateForm)
    },
    async showCurCatePid(obj) {
      let level = obj.cat_level
      let pid = obj.cat_pid
      if (level === 0) {
        this.selecedKeys = []
      } else if (level === 1) {
        this.selecedKeys2 = [pid]
      } else {
        const { data: res } = await this.$http.get('categories/' + pid)
        if (res.meta.status !== 200) return this.$message.error('获取分类信息失败！')
        let ppid = res.data.cat_pid
        this.selecedKeys2 = [ppid, pid]
      }
    },
    clearEditForm() {
      this.$refs.editCateFormRef.resetFields()
      this.selecedKeys2 = []
      this.editCateForm = {}
    },
    // 提交编辑分类
    editCate() {
      this.$refs.editCateFormRef.validate(async validate => {
        if (!validate) return this.$message('您输入的格式有误！')
        const { data: res } = await this.$http.put('categories/' + this.curEditId, {
          cat_name: this.editCateForm.cat_name
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('更新成功！')
        this.editCateDialogVisible = false
        this.getCateList()
      })
    },
    // 删除分类
    delCate(id) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('categories/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败！')
        this.$message.success('删除成功！')
        this.getCateList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
.lightgreen {
  color: lightgreen;
}
.red {
  color: red;
}
body {
  margin: 0;
}
</style>
